package com.pricl.frame.core.mybatis;

import java.lang.reflect.Method;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.aop.MethodBeforeAdvice;

import com.pricl.frame.core.web.Helper;


/**
 * 主从选择切面
 * @author Fu
 *
 */
public class MapperMethodAdvice implements MethodBeforeAdvice{

	
	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		if(DynamicDataSource.slaveFlag){
//			//System.out.println("-------------before");
			MetaObject metaObject = SystemMetaObject.forObject(target);
			Class<?> mapperInterface = (Class<?>) metaObject.getValue("h.mapperInterface");
			String methodName=method.getName();
			String fullMethodName = mapperInterface.getCanonicalName() + "." + methodName;
			SqlSessionFactory ssf=  Helper.getBean(SqlSessionFactoryBean.class).getObject();
			MappedStatement statement=ssf.getConfiguration().getMappedStatement(fullMethodName);
			if(statement!=null){
				if(SqlCommandType.SELECT.equals(statement.getSqlCommandType())){
					//read operation
					DataSourceSelectHolder.setSlave();
					return;
				}
				
			}
			DataSourceSelectHolder.reset();
		}
	}

	
	/*@Override
	public void before(Method method, Object[] args, Object target)throws Throwable {
		String type = null;  
	    String id = null;
	      
	    Annotation[] as = method.getAnnotations();  
	    for (Annotation a : as) {  
	        if (a instanceof DataSourceTarget) {  
	            type = ((DataSourceTarget) a).type();  
	            id = ((DataSourceTarget) a).id();  
	            break ;  
	        }  
	    }  
	      
	    DAOMethodType dsType = null;  
	      
	    if (type != null || id != null) {  
	        dsType = new DAOMethodType(id, type, null);  
	    }  
	    else {  
	        MappedStatement statement = factory.getConfiguration().getMappedStatement(method.getName());  
	        dsType = new DAOMethodType(null, null, statement.getSqlCommandType());  
	    }  
	      
	    if (dsType != null) {  
	        dataSource.setDAOMethodType(dsType);  
	    }  
	}*/

}
